import { mapState, mapActions } from 'vuex';
import moment from 'moment';
// import { withLoading } from '../../utils/request';
import { debounce } from '../../utils';
import * as api from '../../api/channels';
import { withMsg } from '../../utils/request';
import { uniqWith } from 'lodash';

export default {
    data () {
        return {
            searchValue: '',
            loading: false,
            error: false,
            finished: true,
            refreshing: false,
            suggestPopupVisible: false,
            currentId: 0,
            suggestionLoading: false,
            suggestionFinish: true,
            suggestionError: false,
            channelPopupVisible: false,
            editing: false,
            tmpNewMyChannels: [],
            tmpDelMyChannelIds: [],
        };
    },
    computed: {
        ...mapState('articles', [
            'channels',
            'articles',
            'suggestions',
            'myChannels',
        ]),
        showingMyChannels () {
            return uniqWith(
                this.myChannels
                    .filter((channel) => {
                        return !this.tmpDelMyChannelIds.some((id) => channel.id === id);
                    })
                    .concat(this.tmpNewMyChannels)
                    .sort((a, b) => a.id - b.id)
            );
        },
        channelOptions () {
            return this.channels.filter((channel) => {
                return !this.showingMyChannels.some((myChannel) => myChannel.id === channel.id);
            });
        },
    },
    methods: {
        ...mapActions('articles', [
            'updateChannels',
            'updateArticles',
            'search',
            'updateSearchSuggestions',
            'updateMyChannels',
        ]),
        // 刷新
        onRefresh () {
            this.refreshing = false;
            this.onTabChange(this.currentId);
        },
        onMore () {

        },
        timestamp2fromNow (timestamp) {
            return moment(timestamp).fromNow();
        },
        // onTabChange: withLoading(async function (id) {
        //     await this.updateArticles({
        //         channel_id: id,
        //         timestamp: moment().valueOf(),
        //     }).catch(() => {
        //         this.error = true;
        //     });
        // }),
        onDebounceTabChange: debounce(function (id) {
            this.onTabChange(id);
        }, 500),
        async onTabChange (id) {
            this.finished = false;
            this.loading = true;
            await this.updateArticles({
                channel_id: id,
                timestamp: moment().valueOf(),
            }).catch(() => {
                this.error = true;
            });
            this.finished = true;
            this.loading = false;
        },
        onGetSuggestions: debounce(async function (value) {
            if (!value) {
                return;
            }
            this.suggestPopupVisible = true;
            this.suggestionFinish = false;
            this.suggestionLoading = true;
            await this.updateSearchSuggestions(value);
            this.suggestionFinish = true;
            this.suggestionLoading = false;
        }),
        async onSearch (value) {
            this.finished = false;
            this.loading = true;
            if (!value) {
                await this.updateArticles({
                    channel_id: this.channels[0].id,
                    timestamp: moment().valueOf(),
                }).catch(() => {
                    this.error = true;
                });
            } else {
                await this.search(value).catch(() => {
                    this.error = true;
                });
            }
            this.finished = true;
            this.loading = false;
        },
        async onSuggest (suggestion) {
            this.searchValue = suggestion;
            this.suggestPopupVisible = false;

            this.finished = false;
            this.loading = true;
            await this.search(suggestion).catch(() => {
                this.error = true;
            });
            this.finished = true;
            this.loading = false;
        },
        openChannelsPopup () {
            this.channelPopupVisible = true;
            this.updateMyChannels();
        },
        onAddMyChannel (channel) {
            this.tmpNewMyChannels.push(channel);
        },
        onRemoveMyChannel (id) {
            const index = this.tmpNewMyChannels.findIndex((channel) => channel.id === id);
            if (index > -1) {
                this.tmpNewMyChannels.splice(index, 1);
            }
            this.tmpDelMyChannelIds.push(id);
        },
        async onChannelEditFinish () {
            this.editing = false;
            await withMsg(api.saveMyChannels(this.showingMyChannels));
            await this.updateMyChannels();
            this.tmpDelMyChannelIds = [];
            this.tmpNewMyChannels = [];
        },
    },
    async mounted () {
        // 发请求
        await this.updateChannels();
        // withLoading(async function () {
        //     await this.updateArticles({
        //         channel_id: this.channels[0].id,
        //         timestamp: moment().valueOf(),
        //     }).catch(() => {
        //         this.error = true;
        //     });
        // }).call(this);
        this.finished = false;
        this.loading = true;
        await this.updateArticles({
            channel_id: this.channels[0].id,
            timestamp: moment().valueOf(),
        }).catch(() => {
            this.error = true;
        });
        this.finished = true;
        this.loading = false;
    },
}
